package com.xkdx.guangguang.module.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.Environment;
import android.util.Log;

import com.xkdx.guangguang.shareclass.BrandCommentary;
import com.xkdx.guangguang.shareclass.BrandCommentaryResult;
import com.xkdx.guangguang.shareclass.DaZhongBean;
import com.xkdx.guangguang.shareclass.DaZhongDetailBean;
import com.xkdx.guangguang.shareclass.ShopCommentary;
import com.xkdx.guangguang.shareclass.ShopCommentaryResult;
import com.xkdx.guangguang.shareclass.UpLoadHead;

public class ShopCommentUtil {

	private static final String TAG = "ShopCommentUtil";
	private Context context;
	private HttpPost httpPost;
	private HttpClient httpClient;
	HttpResponse response;
	UpLoadHead upLoadHead;

	public ShopCommentUtil(Context context) {
		super();
		this.context = context;
	}

	private void parse(String str) {
		JSONTokener jsonTokener = new JSONTokener(str);
		JSONObject commnetary;
		try {
			commnetary = (JSONObject) jsonTokener.nextValue();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 上传头像
	public UpLoadHead getUploadImage(String url, String json, Bitmap bitmap) {
		Log.i("上传头像", url);
		Log.i("上传头像", json);
		upLoadHead = new UpLoadHead();
		File dirFile = null;
		if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
			dirFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/GuangGuang/comment/");
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}
		}
		try {
			httpPost = new HttpPost(url);

			CompressFormat format = Bitmap.CompressFormat.JPEG;
			int quality = 100;
			OutputStream stream = null;
			try {
				stream = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()
						+ "/GuangGuang/comment/" + "image.jpg");
				// Log.i(TAG, dirFile.getAbsoluteFile().getAbsolutePath());
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (bitmap != null) {
				bitmap.compress(format, quality, stream);
			}
			FileBody fileBody = new FileBody(new File(Environment.getExternalStorageDirectory().getAbsolutePath()
					+ "/GuangGuang/comment/" + "image.jpg"));

			httpClient = new DefaultHttpClient();
			// Log.i(TAG, "bundle-->" + json);

			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("JsonString", json));
			httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

			// MultipartEntity reqEntity = new
			// MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
			// reqEntity.addPart("JsonString", new StringBody(json,
			// Charset.forName(HTTP.UTF_8)));
			// reqEntity.addPart("image", fileBody);

			// httpPost.setEntity(reqEntity);

			response = httpClient.execute(httpPost);
			Log.i(TAG, String.valueOf(response.getStatusLine().getStatusCode()));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		if (response != null && response.getStatusLine().getStatusCode() == 200) {

			try {
				// String strResult =
				// EntityUtils.toString(response.getEntity());
				String strResult = getContent(url, response);
				Log.i(TAG, strResult);
				parse(strResult);
				// return parserUpLoadImage(strResult);
				return null;
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		return upLoadHead;
	}

	public ShopCommentaryResult getShopCommentInfo(String url, String json) {
		// Log.i("commentjson",json);
		ShopCommentaryResult commentResult = new ShopCommentaryResult();
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);
		List<NameValuePair> parmlist = new ArrayList<NameValuePair>();
		parmlist.add(new BasicNameValuePair("JsonString", json));
		try {
			post.setEntity(new UrlEncodedFormEntity(parmlist, HTTP.UTF_8));
			response = httpClient.execute(post);

		} catch (IOException e) {
			e.printStackTrace();
		}
		if (response != null && response.getStatusLine().getStatusCode() == 200) {
			try {
				// String strResult =
				// EntityUtils.toString(response.getEntity());
				String strResult = getContent(url, response);
				Log.i(TAG, strResult);
				return parseAllCommentInfo(strResult);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return commentResult;
	}

	// 解析评论详情内容
	private ShopCommentaryResult parseAllCommentInfo(String str) {
		JSONTokener jsonTokener = new JSONTokener(str);
		JSONObject person;
		ShopCommentaryResult comment = new ShopCommentaryResult();
		List<ShopCommentary> list = new ArrayList<ShopCommentary>();
		try {
			person = (JSONObject) jsonTokener.nextValue();
			JSONObject stut = (JSONObject) person.get("Result");
			JSONArray ListInfo = (JSONArray) stut.getJSONArray("ListInfo");
			JSONObject time = stut.getJSONObject("DetailInfo");
			String lastTime = time.getString("RefreshTime");
			String dataCount = time.getString("DataCount");
			comment.setRefreshTime(lastTime);
			comment.setDataCount(dataCount);
			for (int i = 0; i < ListInfo.length(); i++) {
				JSONObject jsonObj = ((JSONObject) ListInfo.opt(i));
				ShopCommentary commentinfo = new ShopCommentary();
				commentinfo.setCommentContent(jsonObj.getString("CommentContent"));
				commentinfo.setNickName(jsonObj.getString("NickName"));
				commentinfo.setCreateTime(jsonObj.getString("CreateTime"));
				commentinfo.setPictrueUrl(jsonObj.getString("PictureUrl"));
				commentinfo.setUserAvatars(jsonObj.getString("UserAvatars"));
				list.add(commentinfo);
			}
			comment.setShopCommentList(list);

		} catch (Exception e) {
		}

		return comment;
	}

	private UpLoadHead parserUpLoadImage(String str) {
		JSONTokener jsonTokener = new JSONTokener(str);
		JSONObject person;

		try {
			person = (JSONObject) jsonTokener.nextValue();
			if (person == null) {
				return upLoadHead;
			}
			JSONObject stut = (JSONObject) person.get("Result");
			JSONObject detail = (JSONObject) stut.getJSONObject("DetailInfo");

			upLoadHead.setPictureUrl(detail.getString("PictureUrl"));
			upLoadHead.setGrade(detail.getString("Grade"));
			upLoadHead.setGradeTitle(detail.getString("GradeTitle"));
			upLoadHead.setNickName(detail.getString("NickName"));
			upLoadHead.setUserID(detail.getString("UserID"));
			upLoadHead.setMessage(stut.getString("Message"));
			return upLoadHead;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return upLoadHead;
	}

	public BrandCommentaryResult getBrandCommentInfo(String url, String json) {
		Log.i("品牌评论", url);
		Log.i("品牌评论", json);
		BrandCommentaryResult commentResult = new BrandCommentaryResult();
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);
		List<NameValuePair> parmlist = new ArrayList<NameValuePair>();
		parmlist.add(new BasicNameValuePair("JsonString", json));
		try {
			post.setEntity(new UrlEncodedFormEntity(parmlist, HTTP.UTF_8));
			response = httpClient.execute(post);

		} catch (IOException e) {
			e.printStackTrace();
		}
		if (response != null && response.getStatusLine().getStatusCode() == 200) {
			try {
				// String strResult =
				// EntityUtils.toString(response.getEntity());
				String strResult = getContent(url, response);
				Log.i("品牌评论", strResult);
				return parseBrandAllCommentInfo(strResult);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return commentResult;
	}

	// 解析评论详情内容
	private BrandCommentaryResult parseBrandAllCommentInfo(String str) {
		JSONTokener jsonTokener = new JSONTokener(str);
		JSONObject person;
		BrandCommentaryResult comment = new BrandCommentaryResult();
		List<BrandCommentary> list = new ArrayList<BrandCommentary>();
		try {
			person = (JSONObject) jsonTokener.nextValue();
			JSONObject stut = (JSONObject) person.get("Result");
			JSONArray ListInfo = (JSONArray) stut.getJSONArray("ListInfo");
			JSONObject time = stut.getJSONObject("DetailInfo");
			String lastTime = time.getString("RefreshTime");
			String dataCount = time.getString("DataCount");
			comment.setRefreshTime(lastTime);
			comment.setDataCount(dataCount);
			for (int i = 0; i < ListInfo.length(); i++) {
				JSONObject jsonObj = ((JSONObject) ListInfo.opt(i));
				BrandCommentary commentinfo = new BrandCommentary();
				commentinfo.setCommentContent(jsonObj.getString("CommentContent"));
				commentinfo.setNickName(jsonObj.getString("NickName"));
				commentinfo.setCreateTime(jsonObj.getString("CreateTime"));
				commentinfo.setPictrueUrl(jsonObj.getString("PictureUrl"));
				commentinfo.setUserAvatars(jsonObj.getString("UserAvatars"));
				list.add(commentinfo);
			}
			comment.setBrandCommentList(list);

		} catch (Exception e) {
		}

		return comment;
	}

	// 大众点评json解析
	public static DaZhongBean DaZhongParJson(String requestResult) {

		JSONTokener jsonTokener = new JSONTokener(requestResult);
		JSONObject daZhongComment;
		DaZhongBean comment = new DaZhongBean();
		List<DaZhongDetailBean> list = new ArrayList<DaZhongDetailBean>();
		try {
			daZhongComment = (JSONObject) jsonTokener.nextValue();
			JSONArray ListInfo = (JSONArray) daZhongComment.getJSONArray("reviews");
			for (int i = 0; i < ListInfo.length(); i++) {
				JSONObject jsonObj = ((JSONObject) ListInfo.opt(i));
				DaZhongDetailBean commentinfo = new DaZhongDetailBean();
				commentinfo.setReview_id(Long.parseLong(jsonObj.getString("review_id")));
				commentinfo.setUser_nickname(jsonObj.getString("user_nickname"));
				commentinfo.setText_excerpt(jsonObj.getString("text_excerpt"));
				commentinfo.setReview_url(jsonObj.getString("review_url"));
				commentinfo.setCreated_time(jsonObj.getString("created_time"));
				commentinfo.setRating_s_img_url(jsonObj.getString("rating_s_img_url"));
				commentinfo.setReview_rating(jsonObj.getString("review_rating"));
				list.add(commentinfo);
			}
			comment.setDaZhongDetaillist(list);

		} catch (Exception e) {
		}

		return comment;
	}

	private String getContent(String url, HttpResponse response) {
		if (response == null) {
			return null;
		}
		String str = null;
		BufferedReader r = null;
		StringBuffer sb = new StringBuffer();
		HttpEntity entity = response.getEntity();
		if (entity != null) {

			try {
				r = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));

				String line;
				while ((line = r.readLine()) != null) {
					sb.append(line);
				}
				str = sb.toString();
			} catch (IOException e) {
				// Log.i(TAG, String.valueOf(e.getMessage()));
				e.printStackTrace();
			}
		}

		return str;
	}
}
